import * as net from 'net';
import { charLibrary } from './code';

// 检查端口是否可用
const checkPort = (port: number) => {
    return new Promise<boolean>((resolve) => {
        const server = net.createServer()
        .once('error', (err) => {
            if ((err as any).code === 'EADDRINUSE') {
                resolve(false); // 端口占用
            } else {
                resolve(true); // 其他错误
            }
        })
        .once('listening', () => {
            server.close();
            resolve(true); // 端口可用
        })
        .listen(port);
    });
};

// 尝试启动应用，检查端口是否可用，若不可用则递增端口
export async function tryStart (port: number){
    const isPortAvailable = await checkPort(port);
    if (isPortAvailable) {
        return port;
    } else {
        console.log(`Port ${port} is in use. Trying next port...`);
        return tryStart(port + 1);  // 递增端口并重试
    }
};

export function getRandomChineseCharacterFromLibrary(length = 4) {
    let chars = [];
    for (let i = 0; i < length; i++) {
        const randomIndex = Math.floor(Math.random() * charLibrary.length); // 随机选择索引
        chars.push((charLibrary as never)[randomIndex]); // 从字库中选择字符
    }
    return chars.join(''); // 将字符数组转换为字符串
}